
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <pthread.h>

/*
 *  traffic thread
 */
ssize_t *pear_total_send_bytes;
ssize_t *pear_total_receive_bytes;

void pear_traffic_init(void)
{
	// printf("--->%s\n", getenv("pear_total_send_bytes"));
	// printf("--->%s\n", getenv("pear_total_receive_bytes"));

	pear_total_send_bytes = strtol(getenv("pear_total_send_bytes"), NULL, 16);
	pear_total_receive_bytes = strtol(getenv("pear_total_receive_bytes"), NULL, 16);
	unsetenv("pear_total_send_bytes");
	unsetenv("pear_total_receive_bytes");

	// printf("--->%p\n", pear_total_send_bytes);
	// printf("--->%p\n", pear_total_receive_bytes);
}

void *pear_traffic_upload(void *arg)
{
	(void *)arg;

	while (1) {
		printf("pear_total_send_bytes: %ld, pear_total_receive_bytes: %ld\n", 
			*pear_total_send_bytes, 
			*pear_total_receive_bytes);
		sleep(1);
	}

	return NULL;
}


/*
 *  3rd app 
 */
typedef unsigned long (*pear_version_t)(void);
typedef int (*pear_main_t)(int argc, char *argv[]);

#define ARGC 6
static char *argv[ARGC] = {
	"3rd_app", 
	"--mac=20:76:93:93:93:93",									// mac, you can use it as your node flag
	"--install_path=/", 										// option
	"--cache_path=/mnt/sda1/.pear/srv/3rd_app_cache_dir",		// you can store your cache data in ${cache_path}
	"--conf_path=/mnt/sda1/.pear/etc/3rd_app_conf_dir",			// you can store your config data in ${conf_path}
	"--log_path=/mnt/sda1/.pear/var/log/3rd_app_log_dir"		// you can store your log data in ${log_path}
};


void pear_traffic_start(void)
{
	pthread_t tid;
	pthread_create(&tid, NULL, pear_traffic_upload, NULL);
}


int main(void)
{
	// ----> traffic
	//
	pear_traffic_init();
	pear_traffic_start();

	// ---> test
	//
	printf("-------> test \n");
	{
		char buffer[102400];
		memset(buffer, 0, sizeof(buffer));
	}
	printf("=======> test \n");

	// -------> load 3rd_app library
	//
	void *handle = dlopen("./lib3rdapp/lib3rdapp.so", RTLD_NOW);
	if (NULL == handle) {
		printf("dlopen 0 %s\n", dlerror());
		exit(-1);
	}

	// pear_version
	//
	pear_version_t 	pear_version = dlsym(handle, "pear_version");
	printf("3rd app version: %lu\n", pear_version());

	// pear_main 
	//
	pear_main_t pear_main = dlsym(handle, "pear_main");
	pear_main(ARGC, argv);

	sleep(5);

	dlclose(handle);

	return 0;
}








